<template>
  <div class="main-content">
    <AsyncSearchTable :columns="allColumns"
                      :search-items="searchItems"
                      :fetch-data="fetchData">
      <template #status="{ row }">
        <el-tag :type="row.status === '0' ? 'success' : 'danger'">
          {{ row.status === '0' ? '正常' : '停用' }}
        </el-tag>
      </template>
      <template #toolbar>
        <el-button type="primary" :icon="Plus" @click="visible = true">新增</el-button>
        <el-button type="danger" :icon="Delete" @click="handleBatchDelete">批量删除</el-button>
      </template>
      <template #action-column>
        <el-button type="info" link :icon="View">查看</el-button>
        <el-button type="primary" link :icon="Edit">编辑</el-button>
        <el-button type="danger" link :icon="Delete">删除</el-button>
      </template>
    </AsyncSearchTable>
  </div>
</template>

<script setup lang="ts">
import {reactive, ref} from 'vue'
import type {FormInstance, FormRules} from 'element-plus'
import {ElMessage, ElMessageBox} from 'element-plus'
import AsyncSearchTable from '@/components/AsyncSearchTable/index.vue'
import type {TableColumn} from '@/types/table'
import type {SearchItem} from '@/types/search'
import * as http from "@/api/http.ts";
import {Delete, Edit, Plus, View} from "@element-plus/icons-vue";

const tableRef = ref()
const formRef = ref<FormInstance>()
const dialogVisible = ref(false)
const dialogTitle = ref('')

// 表单参数
const form = reactive({
  id: '',
  configName: '',
  configKey: '',
  configValue: '',
  configType: 'Y',
  remark: ''
})

// 表单校验规则
const rules = reactive<FormRules>({
  configName: [
    {required: true, message: '配置名称不能为空', trigger: 'blur'}
  ],
  configKey: [
    {required: true, message: '配置键名不能为空', trigger: 'blur'}
  ],
  configValue: [
    {required: true, message: '配置键值不能为空', trigger: 'blur'}
  ]
})

// 表格列配置
const allColumns: TableColumn[] = [
  {prop: 'configName', label: '配置名称', minWidth: '120'},
  {prop: 'configKey', label: '配置键名', minWidth: '120'},
  {prop: 'configValue', label: '配置键值', minWidth: '120'},
  {prop: 'configType', label: '系统内置', minWidth: '100', slot: 'configType'},
  {prop: 'remark', label: '备注', minWidth: '120'},
  {prop: 'createdTime', label: '创建时间', minWidth: '160'}
]

// 搜索项配置
const searchItems: SearchItem[] = [
  {
    field: 'configName',
    label: '配置名称',
    type: 'input',
    placeholder: '请输入配置名称'
  },
  {
    field: 'configKey',
    label: '配置键名',
    type: 'input',
    placeholder: '请输入配置键名'
  },
  {
    field: 'configType',
    label: '系统内置',
    type: 'select',
    options: [
      {label: '是', value: 'Y'},
      {label: '否', value: 'N'}
    ]
  }
]


// 获取数据
const fetchData = async (params: any) => {
  try {
    const response = await http.get('/api/system/config')
    console.log(response.data);
    console.log(response);
    return response.data
  } catch (error) {
    console.error('获取数据失败:', error)
    return {
      list: [],
      total: 0
    }
  }
}

// 新增按钮操作
function handleAdd() {
  dialogTitle.value = '添加配置'
  dialogVisible.value = true
  form.id = ''
  form.configName = ''
  form.configKey = ''
  form.configValue = ''
  form.configType = 'Y'
  form.remark = ''
}

// 修改按钮操作
function handleEdit(row: any) {
  dialogTitle.value = '修改配置'
  dialogVisible.value = true
  Object.assign(form, row)
}

// 删除按钮操作
function handleDelete(row: any) {
  ElMessageBox.confirm('确认要删除该配置吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await fetch(`/api/system/config/${row.id}`, {
        method: 'DELETE'
      })
      const data = await response.json()
      if (data.code === 200) {
        ElMessage.success('删除成功')
        handleRefresh()
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 刷新按钮操作
function handleRefresh() {
  tableRef.value?.refresh()
}

// 表单提交
async function submitForm() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const url = form.id ? '/api/system/config' : '/api/system/config'
        const method = form.id ? 'PUT' : 'POST'
        const response = await fetch(url, {
          method,
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(form)
        })
        const data = await response.json()
        if (data.code === 200) {
          ElMessage.success(form.id ? '修改成功' : '添加成功')
          dialogVisible.value = false
          handleRefresh()
        }
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败')
      }
    }
  })
}

// 取消按钮
function cancel() {
  dialogVisible.value = false
  formRef.value?.resetFields()
}
</script>

<style scoped>
</style> 